import { createSlice, createAsyncThunk, SliceCaseReducers } from '@reduxjs/toolkit';
import { TabPaneProps } from 'antd';

interface Tabs extends TabPaneProps {
  key: string;
  url: string;
}
interface User {
  userInfo: {
    user?: {
      [K: string]: any;
    };
    permissions?: string[];
    roles?: string[];
  };
  menu: any;
  menuTree: any[];
  tabList: Tabs[];
  routers: any[];
}

// 获取用户信息的action
export const getUserInfo = createAsyncThunk('user/getUserInfo', async () => {
  const info = await $get('/getInfo');
  const init: any = {};
  if (info.code === 200) {
    init.userInfo = info;
  }
  return init;
});

// 获取菜单数据的actions
export const getMenus = createAsyncThunk('user/getMenus', async () => {
  const res = await $get('/system/menu/list');
  if (res.code === 200) {
    return res;
  }
  return res;
});

// 获取路由表信息
export const getRouters = createAsyncThunk('user/getRouter', async () => {
  const res = await $get('/getRouters');
  if (res.code === 200) {
    return res.data;
  }
  return res;
});

// 获取菜单tree结构的action
export const getMenuTree = createAsyncThunk('user/getMenuTree', async () => {
  const res = await $get('/system/menu/treeselect');

  const transfer = (list: any[]) => {
    let temp: { value: any; label: any; children: any[] }[] = [];
    list.forEach(d => {
      const child = d.children ? [...transfer(d.children)] : undefined;
      temp.push({
        value: d.id,
        label: d.label,
        children: child,
      });
    });
    return temp;
  };
  return transfer(res.data);
});

export const userSlice = createSlice<User, SliceCaseReducers<User>, string>({
  name: 'user',
  initialState: {
    userInfo: {},
    menu: [],
    menuTree: [],
    tabList: [],
    routers: [],
  },
  reducers: {
    appendTreeMenu: (state, action) => {
      state.menuTree = action.payload;
    },
    addTabs: (state, action) => {
      state.tabList.push(action.payload);
    },
  },
  extraReducers(builder) {
    // 获取用户信息
    builder
      .addCase(getUserInfo.fulfilled, (state, res) => {
        state.userInfo = res.payload.userInfo;
      })
      .addCase(getMenus.fulfilled, (state, res) => {
        state.menu = res.payload.data;
      })
      .addCase(getRouters.fulfilled, (state, res) => {
        state.routers = res.payload;
      })
      .addCase(getMenuTree.fulfilled, (state, res) => {
        state.menuTree = res.payload;
      })
      .addCase(getUserInfo.rejected, (_s, err) => {
        console.error(err);
      })
      .addCase(getMenus.rejected, (_s, err) => {
        console.error(err);
      })
      .addCase(getMenuTree.rejected, (_s, err) => {
        console.error(err);
      });
  },
});
export const { appendTreeMenu, addTabs, addKeyPath } = userSlice.actions;
export default userSlice.reducer;
